package com.heima.user.service.impl;
import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.admin.dtos.PageResponseResult;
import com.heima.model.admin.dtos.ResponseResult;
import com.heima.model.admin.enums.AppHttpCodeEnum;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        dto.checkParam();  //分页参数

        // 2 封装查询条件
        //2.1 分页条件
        Page<ApUserRealname> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //2.2 status
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        //如果status不为空   按照状态查询
        queryWrapper.eq(dto.getStatus() !=null,ApUserRealname::getStatus,dto.getStatus());
        //3:执行查询
        IPage<ApUserRealname> pageResult = this.page(pageReq, queryWrapper);
        //封装结果

        return new PageResponseResult(dto.getPage(), dto.getSize(),
               pageResult.getTotal(), pageResult.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;
   // @Transactional
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)  //开启全局事务
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {

        //1:检查参数
        //1.1: 检查id
        if(dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //1.2 根据id 查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        //1.3 检查状态  1:待审核 2失败  9审核通过
        if(!userRealname.getStatus().equals(AdminConstants.WAIT_AUTH)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证状态错误");
        }
        //1.4 查询关联的apUser信息  注入ApUserMapper对象
        ApUser apUser = apUserMapper.selectById(userRealname.getId());
            if(apUser==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联的app用户信息不存在");
            }
            //修改实名认证的状态
             userRealname.setStatus(status);
            //消息不为空  设置消息
        if(StringUtils.isNotBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());
        }
        //修改实名认证状态
        updateById(userRealname);
        //判断是否通过审核
        if(userRealname.getStatus().equals(AdminConstants.USER_STATUS_ISSTATUS)){
            // TODO:  9:   远程开通自媒体账号 (创建一个方法)
           WmUser wmUser= createWmUser(apUser);  //返回自媒体账户
            //  TODO: 创建作者信息  // ap_user   wm_user
            createAuthor(wmUser,apUser);

        }

        System.out.println(1/0);
        return ResponseResult.okResult();
    }


    //注入远程Feign接口
    @Autowired
    ArticleFeign articleFeign;
    /**
     * 创建作者
     * */
    private void createAuthor(WmUser wmUser, ApUser apUser) {
        //1:远程查询作者信息是否存在
        ResponseResult<ApAuthor> authorResult = articleFeign.findByUserId(apUser.getId());
        if (authorResult.getCode().intValue()!=0) {
            //不等于0  远程调用出错
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,authorResult.getErrorMessage());
        }
        //查看作者信息有没有
        ApAuthor apAuthor = authorResult.getData();
            if(apAuthor!=null){  //说明作者信息已存在
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者信息已经存在");
            }
                //创建作者信息
                    apAuthor=new ApAuthor();
                apAuthor.setName(apUser.getName());
                apAuthor.setType(2);  //类型  :  平台自媒体人
                apAuthor.setUserId(apUser.getId());
                apAuthor.setCreatedTime(new Date());
                apAuthor.setWmUserId(wmUser.getId());  //对应的自媒体用户
                //保存作者信息
        ResponseResult<ApAuthor> saveResult = articleFeign.saveAuthor(apAuthor);
        if(saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,saveResult.getErrorMessage());
        }

}

    /**
     *
        * 远程创建自媒体账户
         * 注入Feign
        * */
        @Autowired
    WemediaFeign wemediaFeign;
    private WmUser createWmUser(ApUser apUser) {
        //1:  查询关联自媒体账户是否已经创建
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if (wmUserResult.getCode().intValue()!=0) {
            //状态不对直接抛异常.不往下走了
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser = wmUserResult.getData();


        if(wmUser!=null){  //说明自媒体账户已经存在了
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体账户已经存在");
        }
        //2:no 创建自媒体账户
      wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);//设置为9  正常状态
        wmUser.setType(0);  //设置为0   类型: 个人
        wmUser.setCreatedTime(new Date());
            //用Feign远程调用保存方法
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,saveResult.getErrorMessage());
        }
            //2:创建自媒体用户
        return saveResult.getData();//已经设置了id的 wmUser对象
    }
}